<!--
 @description 日期时间选择
 @fileName index.vue
 @author zengqiongying
 @created 2022/11/17 13:56:54
-->
<template>
  <div class="field-calendar">
    <div class="input-field">
      <van-field
        v-model="startValue"
        :class="['field',valueClassName]"
        label=""
        :placeholder="['daterange','datetimerange'].includes(type)?startPlaceholder:placeholder"
        :left-icon="iconPosition==='left'?'calendar-o':''"
        :right-icon="iconPosition==='right'?'calendar-o':''"
        readonly
        @click.native="openCaledar"
      />
      <div v-if="showClear" class="btn-clear" @click.stop="handleClearValue">
        <svg-icon icon-class="cuowuguanbiquxiao-solid_" />
      </div>
    </div>
    <template v-if="['daterange','datetimerange'].includes(type)">
      <div :class="['sep',{'separator':!!(rangeSeparator)}]">
        {{ rangeSeparator }}
      </div>
      <div class="input-field">
        <van-field
          v-model="endValue"
          :class="['field',valueClassName]"
          label=""
          :left-icon="iconPosition==='left'?'calendar-o':''"
          :right-icon="iconPosition==='right'?'calendar-o':''"
          :placeholder="endPlaceholder"
          readonly
          @click.native="openCaledar"
        />
        <div v-if="showClear" class="btn-clear" @click.stop="handleClearValue">
          <svg-icon icon-class="cuowuguanbiquxiao-solid_" />
        </div>
      </div>
    </template>

    <PopDateTimePicker
      v-model="showDate"
      :title="title"
      :default-value="defaultDate"
      :min-date="curMinDate"
      :max-date="curMaxDate"
      :calendar-type="calendarType"
      :show-time="showTime"
      :clear="showClear"
      @change="onConfirmDate"
    />
  </div>
</template>

<script>
import PopDateTimePicker from '../PopDateTimePicker'
import { parseTime } from '@/utils'
export default {
  name: 'FieldCalendarTime',
  components: { PopDateTimePicker },
  props: {
    title: {
      type: String,
      default: '日期'
    },
    value: {
      type: [String, Array],
      default: ''
    },
    valueClassName: {
      type: String,
      default: ''
    },
    minDate: {
      type: Date,
      default: null
    },
    maxDate: {
      type: Date,
      default: null
    },
    type: {
      type: String,
      default: 'date' // 日期类型（date 单个日期，daterange 日期范围,datetime  日期时间，datetimerange 日期时间范围）
    }, // 日历选择类型：single表示选择单个日期，range 表示选择日期区间,multiple表示选择多个日期(暂不支持)

    defaultDate: {
      type: [String, Array],
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '选择日期'
    },
    startPlaceholder: {
      type: String,
      default: '选择日期'
    },
    endPlaceholder: {
      type: String,
      default: '选择日期'
    },
    clear: {
      // 是否显示清除按钮
      type: Boolean,
      default: false
    },
    iconPosition: {
      // 日历图标位置：left /right
      type: String,
      default: ''
    },
    rangeSeparator: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      startValue: '',
      endValue: '',
      showDate: false,
      caledarMinDate: '',
      caledar: {
        show: false,
        title: '',
        defaultData: null
      }
    }
  },

  computed: {
    curMinDate() {
      if (this.minDate) {
        return this.minDate
      }
      const date = new Date()
      const sDate = new Date().setFullYear(date.getFullYear() - 2)
      return new Date(sDate)
    },
    curMaxDate() {
      if (this.maxDate) {
        return this.maxDate
      }
      const date = new Date()
      const sDate = new Date().setMonth(date.getMonth() + 6)
      return new Date(sDate)
    },
    showTime() {
      return this.type === 'datetime' || this.type === 'datetimerange'
    },
    calendarType() {
      if (this.type === 'datetime' || this.type === 'date') {
        return 'single'
      }
      if (this.type === 'datetimerange' || this.type === 'daterange') {
        return 'range'
      }
      return 'single'
    },
    showClear() {
      if (this.disabled || !this.clear) return false
      if (this.value instanceof Array) {
        return this.value.length > 0
      }
      return !!(this.value)
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val instanceof Array) {
          if (val.length === 2) {
            this.startValue = val[0]
            this.endValue = val[1]
          } else {
            this.startValue = ''
            this.endValue = ''
          }
        } else {
          this.startValue = val
          this.endValue = ''
        }
      },
      immediate: true
    }
  },

  created() {
    const date = new Date()
    const mDate = date.setFullYear(date.getFullYear() - 2)
    this.caledarMinDate = new Date(mDate)
  },
  activated() {},

  mounted() {},

  methods: {
    // 打开日历选择器
    openCaledar(t) {
      const d = new Date()
      let defVal = []
      if (this.type === 'range') {
        if (this.startValue && this.endValue) {
          defVal = [new Date(this.startValue), new Date(this.endValue)]
        }
        if (defVal.length === 0) {
          defVal = [d, d]
        }
      } else {
        defVal = d
      }
      this.caledar = {
        show: true,
        title: this.title,
        defaultData: defVal
      }
      if (this.disabled) return
      this.showDate = true
    },
    // 确认日历选择
    onConfirmCaledar(date) {
      if (this.type === 'range') {
        const [start, end] = date
        const value1 = parseTime(start, '{y}-{m}-{d}')
        const value2 = parseTime(end, '{y}-{m}-{d}')
        this.$set(this.$data, 'startValue', value1)
        this.$set(this.$data, 'endValue', value2)
        this.$emit('input', [this.startValue, this.endValue])
      } else {
        const value1 = parseTime(date, '{y}-{m}-{d}')
        this.$set(this.$data, 'startValue', value1)
        this.$emit('input', this.startValue)
      }

      this.$nextTick(() => {
        this.caledar = {
          show: false,
          title: '',
          defaultData: null
        }
      })
    },
    onConfirmDate(date) {
      if (this.type === 'daterange') {
        this.startValue = parseTime(date[0], '{y}-{m}-{d}')
        this.endValue = parseTime(date[1], '{y}-{m}-{d}')
      } else if (this.type === 'datetimerange') {
        this.startValue = parseTime(date[0], '{y}-{m}-{d} {h}:{i}:{s}')
        this.endValue = parseTime(date[1], '{y}-{m}-{d} {h}:{i}:{s}')
      } else if (this.type === 'datetime') {
        this.startValue = parseTime(date, '{y}-{m}-{d} {h}:{i}:{s}')
      } else {
        this.startValue = parseTime(date, '{y}-{m}-{d}')
      }
      this.$emit('input', date)
      this.showDate = false
    },
    handleClearValue() {
      this.startValue = ''
      this.endValue = ''
      if (this.type === 'range') {
        this.$emit('input', [])
      } else {
        this.$emit('input', '')
      }
    }
  }
}

</script>
<style lang='less' scoped>
  .field-calendar{
    position: relative;
    width: 100%;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .input-field{
      flex: 1;
      position: relative;
    }
    .field{
      height: 36px;
      line-height: 1;
      background: rgba(241, 241, 242, .5);
      /deep/.van-field__left-icon{
        margin-left: -6px;
      }
    }
    .sep{
      margin: 0 10px;
      width: 20px;
      height: 2px;
      background: #B5B7C4;
      border-radius: 1px;
      &.separator{
        height: 20px;
        line-height: 20px;
        width: auto;
        min-width: 20px;
        background: transparent;
        border-radius:0;
        color:#999 ;
      }
    }
    .btn-clear{
      position: absolute;
      z-index: 1;
      right: 0;
      top: 0;
      bottom: 0;
      width: 26px;
      display: flex;
      align-items: center;
      justify-content: center;
      .svg-icon{
        font-size: 14px;
        color: #c5c5c5;
      }
    }
  }
</style>
